/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package domain.controllers;

import domain.Entity.EntityTarea;
import domain.commands.TareaComando;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import managers.TareaManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author jorge
 */
public class etiquetarController extends SimpleFormController {

   public etiquetarController() {
        setCommandClass(TareaComando.class);
  }
  
    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, org.springframework.validation.BindException errors) throws Exception {
   
        TareaManager tm = TareaManager.getInstance();
        ModelAndView mav = new ModelAndView();
        TareaComando tc = (TareaComando) command;
        
        HttpSession session = request.getSession();
        EntityTarea et = (EntityTarea) session.getAttribute("tarea");
        
        
        String etiqueta = "" ;
        
        String etiquetasTarea = et.getEtiquetas();
        List l = new ArrayList();
        StringTokenizer st = new StringTokenizer(etiquetasTarea);
        while(st.hasMoreTokens()){
            String s = st.nextToken();
                l.add(s);
        }
        
        StringTokenizer st2 = new StringTokenizer(tc.getEtiqueta());
        while(st2.hasMoreTokens()){
            String s = st2.nextToken();
            if(!l.contains(s)){
                l.add(s);
            }
        }
        Collections.sort(l);
        Iterator it = l.iterator();
        while(it.hasNext()){
            etiqueta = etiqueta.concat((String) it.next()+" ");
        }
        et.setEtiquetas(etiqueta);
        tm.etiquetar(et);
        mav.setView(new RedirectView("mostrarTareas.htm"));
            
        
        return mav;
    }

    
    
}
